package com.googlecode.garbagecan.cxfstudy.network;

import org.apache.cxf.endpoint.Server;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
import org.apache.cxf.jaxws.JaxWsServerFactoryBean;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Test {

	private static final String address = "http://localhost:12345/ws/networkService";

	public static void main(String[] args) throws Exception {
		startServer();
		startClient();
		System.exit(0);
	}

	private static void startServer() throws Exception {
		System.out.println("Starting Server");

		JaxWsServerFactoryBean factoryBean = new JaxWsServerFactoryBean();
		factoryBean.setServiceClass(NetworkServiceImpl.class);
		factoryBean.setAddress(address);

		Server server = factoryBean.create();
		String endpoint = server.getEndpoint().getEndpointInfo().getAddress();

		System.out.println("Server started at " + endpoint);
	}

	private static void startClient() throws Exception {
		StringBuffer sb = new StringBuffer();
		String data = "";
		while(true) {
			sb.append(System.currentTimeMillis());
			if (sb.length() >= 1024) {
				data = sb.substring(0, 1024);
				break;
			}
		}

		List<Float> speedList = new ArrayList<Float>();
		float totalTime = 0.00f;
		int count = 10;
		for (int i = 0; i < count; i++) {
			long start = System.currentTimeMillis();
			//testByByte(data.getBytes());
			testByString(data);
			long stop = System.currentTimeMillis();
			long time = stop - start;
			float speed = data.length() * 1.0f / time;
			totalTime += speed;
			speedList.add(speed);
		}
		Collections.sort(speedList);
		System.out.println(speedList);

		float avg = totalTime / count;
		System.out.printf("min: %.2f/ms \n", speedList.get(0));
		System.out.printf("max: %.2f/ms \n", speedList.get(count - 1));
		System.out.printf("avg: %.2f/ms \n", avg);
	}

	private static void testByString(String data) throws Exception {
		JaxWsProxyFactoryBean factoryBean = new JaxWsProxyFactoryBean();
		factoryBean.setAddress(address);
		factoryBean.setServiceClass(NetworkService.class);
		Object obj = factoryBean.create();
		NetworkService networkService = (NetworkService) obj;
		networkService.testByString(data);
	}

	private static void testByByte(byte[] data) throws Exception {
		JaxWsProxyFactoryBean factoryBean = new JaxWsProxyFactoryBean();
		factoryBean.setAddress(address);
		factoryBean.setServiceClass(NetworkService.class);
		Object obj = factoryBean.create();
		NetworkService networkService = (NetworkService) obj;
		networkService.testByByte(data);
	}
}
